@(repository: gitbucket.core.service.RepositoryService.RepositoryInfo,
  completionContext: String, generateScript: Boolean = true)(textarea: Html)(implicit context: gitbucket.core.controller.Context)
@import gitbucket.core.util.FileUtil
@import gitbucket.core.view.helpers
<div class="muted attachable">
  @textarea
  <div class="clickable">Attach images or documents by dragging &amp; dropping, or selecting them.</div>
</div>
@defining("(id=\")([\\w\\-]*)(\")".r.findFirstMatchIn(textarea.body).map(_.group(2))){ textareaId =>
<script>
$(function(){
  @gitbucket.core.plugin.PluginRegistry().getSuggestionProviders.map { provider =>
    @if(provider.context.contains(completionContext)){
      var @provider.id = @Html(helpers.json(provider.options(repository).map { case (value, label) =>
        Map("value" -> value, "label" -> label)
      }));
      @Html(provider.additionalScript(repository))
    }
  }
  $('#@textareaId').textcomplete([
    @gitbucket.core.plugin.PluginRegistry().getSuggestionProviders.map { provider =>
      @if(provider.context.contains(completionContext)){
        {
          id: '@{provider.id}',
          match: /\B@{provider.prefix}([\-+\w]*)$/,
          search: function (term, callback) {
            callback($.map(@{provider.id}, function (proposal) {
              return proposal.value.indexOf(term) === 0 ? proposal : null;
            }));
          },
          template: function (option) {
            return @{Html(provider.template)};
          },
          replace: function (option) {
            return '@{provider.prefix}' + @{Html(provider.replace)} + '@{provider.suffix}';
          },
          index: 1
        },
      }
    }
  ], {
    onKeydown: function (e, commands) {
      if (e.ctrlKey && e.keyCode === 74) { // CTRL-J
        return commands.KEY_ENTER;
      }
    }
  });

  @if(generateScript){
    try {
      $([$('#@textareaId')[0]]).dropzone({
        @dropzone(false, textareaId)
      });
      $([$('#@textareaId').closest('div')[0], $('#@textareaId').next('div')[0]]).dropzone({
        @dropzone(true, textareaId)
      });
    } catch(e) {
      if (e.message !== "Dropzone already attached.") {
        throw e;
      }
    }
  }
});

  $('#@textareaId').bind('paste', function(e){
    const items = e.originalEvent.clipboardData.items;
    for (var i = 0; i < items.length; i++) {
      const item = items[i];
      if (item.type.indexOf('image') != -1) {
        const file = item.getAsFile();
        const formData = new FormData();
        formData.append('file', file);

        $.ajax({
          url: '@context.path/upload/file/@repository.owner/@repository.name',
          type: 'POST',
          contentType: false,
          processData: false,
          data: formData,
          success: function(id) {
            const attachFile = `\n![${file.name.split('.')[0]}](@context.baseUrl/@repository.owner/@repository.name/_attached/${id})`;
            $('#@textareaId').val($('#@textareaId').val() + attachFile);
          }
        });
      }
    }
  });
</script>
}
@dropzone(clickable: Boolean, textareaId: Option[String]) = {
  url: '@context.path/upload/file/@repository.owner/@repository.name',
  maxFilesize: @{context.settings.upload.maxFileSize / 1024 / 1024},
  timeout: @{context.settings.upload.timeout},
  clickable: @clickable,
  previewTemplate: "<div class=\"dz-preview\">\n  <div class=\"dz-progress\"><span class=\"dz-upload\" data-dz-uploadprogress>Uploading your files...</span></div>\n  <div class=\"dz-error-message\"><span data-dz-errormessage></span></div>\n</div>",
  success: function(file, id) {
    var attachFile = (file.type.match(/image\/.*/) ? '\n![' + file.name.split('.')[0] : '\n[' + file.name) +
        '](@context.baseUrl/@repository.owner/@repository.name/_attached/' + id + ')';
    $('#@textareaId').val($('#@textareaId').val() + attachFile);
    $(file.previewElement).prevAll('div.dz-preview').addBack().remove();
  }
}
